# -*- Mode: Python -*- vi:si:et:sw=4:sts=4:ts=4:syntax=python
import shutil
from pathlib import Path

from cerbero.utils import shell

class Recipe(recipe.Recipe):
    name = 'gettext-tools'
    version = '0.20.1'
    licenses = [License.GPLv3Plus]
    #srcdir = 'gettext-tools'
    stype = SourceType.TARBALL
    url = 'gnu://gettext/gettext-%(version)s.tar.xz'
    tarball_dirname = 'gettext-%(version)s'
    tarball_checksum = '53f02fbbec9e798b0faaf7c73272f83608e835c6288dd58be6c9bb54624a3800'

    deps = ['automake', 'autoconf', 'm4']
    platform_deps = {Platform.DARWIN:  ['sed'],
                     Platform.WINDOWS: ['libiconv'],}
    configure_options = ' --disable-java --disable-csharp --disable-native-java --without-csv'
    patches = [name + '/0001-Undefine-__USE_MINGW_ANSI_STDIO-as-otherwise-stdio.h.patch',
               name + '/0001-gnulib-tests-undef-MinGW-s-dummy-pthread_sigmask-def.patch',]

    files_bins = [
        'autopoint', 'gettextize', 'msgattrib', 'msgcat', 'msgcmp', 'msgcomm',
        'msgconv', 'msgen', 'msgexec', 'msgfilter', 'msgfmt', 'msggrep',
        'msginit', 'msgmerge', 'msgunfmt', 'msguniq', 'recode-sr-latin',
        'xgettext'
    ]
    override_libtool = False

    def prepare(self):
        if self.config.target_platform == Platform.WINDOWS:
            self.configure_options += ' --enable-threads=win32'

    def post_install(self):
        if self.config.platform == Platform.WINDOWS:
            # The msgmerge built by us randomly hangs on Windows when called
            # during configure, so move it away. msgmerge from MSYS-MinGW
            # will be picked up instead which works fine.
            # NOTE: We cannot copy it into build_tools/bin because then it will
            # try to pick up libintl-8.dll from the windows_x86 prefix.
            build_tools_bin = Path(self.config.build_tools_prefix) / 'bin'
            msys_mingw_bindir = Path(shutil.which('mingw-get')).parent
            msys_msgmerge = msys_mingw_bindir / 'msgmerge.exe'
            if msys_msgmerge.is_file():
                if (build_tools_bin / 'msgmerge.exe').is_file():
                    os.replace(str(build_tools_bin / 'msgmerge.exe'),
                               str(build_tools_bin / 'msgmerge.exe.bck'))
        super().post_install()
